package com.illtamer.infinite.sillage.controller.admin;

import com.illtamer.infinite.sillage.annotation.SecurityUser;
import com.illtamer.infinite.sillage.entity.AjaxResult;
import com.illtamer.infinite.sillage.pojo.Tag;
import com.illtamer.infinite.sillage.pojo.User;
import com.illtamer.infinite.sillage.service.TagService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller("adminTagController")
@RequestMapping("/admin/tags")
public class TagController {

    @Resource(name = "tagService")
    private TagService tagService;

    @RequestMapping
    public String types(@SecurityUser User user,
                        @RequestParam(name = "index", required = false, defaultValue = "1") Integer index, Model model) {
        model.addAttribute("avatar", user.getAvatar());
        // specify
        model.addAttribute("pages", tagService.listThinTags(index, 10));
        return "admin/tags";
    }

    @ResponseBody
    @PostMapping("/save")
    public AjaxResult insert(@RequestParam("name") String name, @RequestParam(name = "id", required = false) Integer id) {
        Tag tag = new Tag();
        tag.setName(name);
        if (id != null) {
            tag.setId(id);
            return tagService.updateEntity(id, tag) != null ? AjaxResult.success("修改成功") : AjaxResult.warn("未找到类型");
        }
        Boolean saved = tagService.saveEntity(tag);
        return saved ? AjaxResult.success() : AjaxResult.warn("类型已存在");
    }

    @ResponseBody
    @PostMapping("/delete")
    public AjaxResult delete(@RequestParam("id") Integer id) {
        Boolean saved = tagService.deleteEntity(id);
        return saved ? AjaxResult.success() : AjaxResult.warn("数据源不存在");
    }

}
